package com.legal.app.service.impl;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Comparator;
import java.text.SimpleDateFormat;
import com.legal.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.legal.app.mapper.MessageMapper;
import com.legal.app.domain.Message;
import com.legal.app.service.IMessageService;
import com.legal.app.domain.vo.MessageSendVO;
import com.legal.app.domain.vo.MessageReadVO;
import com.legal.app.mapper.OrderMapper;
import com.legal.app.domain.Order;
import com.legal.app.domain.vo.MessageListItemVO;
import com.legal.app.mapper.UserMapper;
import com.legal.app.domain.User;

/**
 * 消息Service业务层处理
 * 
 * @author ALe
 * @date 2025-05-30
 */
@Service
public class MessageServiceImpl implements IMessageService {
    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 查询消息
     * 
     * @param id 消息主键
     * @return 消息
     */
    @Override
    public Message selectMessageById(Long id) {
        return messageMapper.selectMessageById(id);
    }

    /**
     * 查询消息列表
     * 
     * @param message 消息
     * @return 消息
     */
    @Override
    public List<Message> selectMessageList(Message message) {
        return messageMapper.selectMessageList(message);
    }

    /**
     * 新增消息
     * 
     * @param message 消息
     * @return 结果
     */
    @Override
    public int insertMessage(Message message) {
        message.setCreateTime(DateUtils.getNowDate());
        return messageMapper.insertMessage(message);
    }

    /**
     * 修改消息
     * 
     * @param message 消息
     * @return 结果
     */
    @Override
    public int updateMessage(Message message) {
        return messageMapper.updateMessage(message);
    }

    /**
     * 批量删除消息
     * 
     * @param ids 需要删除的消息主键
     * @return 结果
     */
    @Override
    public int deleteMessageByIds(Long[] ids) {
        return messageMapper.deleteMessageByIds(ids);
    }

    /**
     * 删除消息信息
     * 
     * @param id 消息主键
     * @return 结果
     */
    @Override
    public int deleteMessageById(Long id) {
        return messageMapper.deleteMessageById(id);
    }

    @Override
    public int sendMessage(MessageSendVO vo, Long senderId) {
        Order order = orderMapper.selectOrderById(vo.getOrderId());
        if (order == null)
            return 0;
        Long receiverId = order.getUserId().equals(senderId) ? order.getLawyerId() : order.getUserId();
        Message message = new Message();
        message.setSenderId(senderId);
        message.setReceiverId(receiverId);
        message.setOrderId(vo.getOrderId());
        message.setContent(vo.getContent());
        message.setMessageType(1L);
        message.setStatus(1L);
        message.setIsSystem(0L);
        message.setCreateTime(new java.util.Date());
        return messageMapper.insertMessage(message);
    }

    @Override
    public int readMessage(Long messageId, Long userId) {
        Message message = messageMapper.selectMessageById(messageId);
        if (message == null || !message.getReceiverId().equals(userId))
            return 0;
        message.setStatus(2L);
        return messageMapper.updateMessage(message);
    }

    @Override
    public List<MessageListItemVO> getMessageSessionList(Long userId) {
        // 1. 查询所有与当前用户有关的消息
        List<Message> allMessages = messageMapper.selectMessageList(new Message());
        Map<Long, List<Message>> sessionMap = new HashMap<>();
        for (Message msg : allMessages) {
            if (!msg.getSenderId().equals(userId) && !msg.getReceiverId().equals(userId))
                continue;
            Long otherId = msg.getSenderId().equals(userId) ? msg.getReceiverId() : msg.getSenderId();
            sessionMap.computeIfAbsent(otherId, k -> new ArrayList<>()).add(msg);
        }
        List<MessageListItemVO> result = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        for (Map.Entry<Long, List<Message>> entry : sessionMap.entrySet()) {
            Long otherId = entry.getKey();
            List<Message> msgs = entry.getValue();
            msgs.sort(Comparator.comparing(Message::getCreateTime).reversed());
            Message lastMsg = msgs.get(0);
            int unread = 0;
            for (Message m : msgs) {
                if (m.getReceiverId().equals(userId) && m.getStatus() != null && m.getStatus() == 1L)
                    unread++;
            }
            User otherUser = userMapper.selectUserById(otherId);
            MessageListItemVO vo = new MessageListItemVO();
            vo.setUserId(otherId);
            vo.setNickName(otherUser != null ? otherUser.getNickName() : "");
            vo.setAvatarUrl(otherUser != null ? otherUser.getAvatarUrl() : "");
            vo.setContent(lastMsg.getContent());
            vo.setTime(lastMsg.getCreateTime() != null ? sdf.format(lastMsg.getCreateTime()) : "");
            vo.setUnreadCount(unread);
            result.add(vo);
        }
        result.sort(Comparator.comparing(MessageListItemVO::getTime).reversed());
        return result;
    }
}
